package com.jdls.tanhua.dubbo.impl;

import cn.hutool.core.collection.CollUtil;
import com.jdls.tanhua.dubbo.VisitorsApi;
import com.jdls.tanhua.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author 嘉德罗斯
 * @date 2021/11/3
 */
@DubboService
public class VisitorsImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate ;

    @Override
    public void save(Visitors visitors) {
        mongoTemplate.save(visitors);
    }

    @Override
    public List<Visitors> findByIds(Long date,Long userId,String format) {
        Criteria criteria = Criteria.where("userId").is(userId).and("isFind").is(0);
        if (date!=null){
            criteria.and("date").gt(date);
        }
        Query query= Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }

    @Override
    //查询当日是否多次访问同一个人
    public Visitors find(Long id, String format,String from,Long userId) {
        Query query = Query.query(Criteria.where("userId").is(id)
                .and("visitorUserId").is(userId)
                .and("visitDate").is(format)
                .and("from").is(from));
        Visitors visitors = mongoTemplate.findOne(query, Visitors.class);

        return visitors;
    }

    @Override
    public void update(Visitors visitors) {
        Update update = Update.update("date",visitors.getDate());
        update.set("isFind",visitors.getIsFind());
        Query query = Query.query(Criteria.where("id").is(visitors.getId()));
        mongoTemplate.updateFirst(query,update,Visitors.class);
    }

    @Override
    public List<Visitors> findById(Long userId,int page, int pageSize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("date")));
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }

    @Override
    public List<Visitors> findById(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }
}
